#!/bin/bash
#
# Implements a garbage-collecting management system for temporary files and
# directories, so that functions using and passing temporary files do not
# have to track them for manual removal.
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.


declare -a -g GC_TEMPFILES
register_cleanup_hook tempfile_cleanup


## s_mktempfile
##
## Creates a temporary file, echoing the filename and returning 0 on success
## (non-zero on failure). Calls mktemp(1), but also registers the filename
## in an array, so that the temporary file can be garbage collected whenever
## stdlib_cleanup is called.
##
function s_mktempfile() {
	local tmpname=$(mktemp -p "${P_TEMPDIR}")
	local status=$?
	GC_TEMPFILES+=("${tmpname}")
	echo "${tmpname}"
	return ${status}
}


## s_mktempdir
##
## Creates a temporary directory, echoing the filename and returning 0 on
## success (non-zero on failure). Calls mktemp(1), but also registers the
## filename in an array, so the temporary file can be garbage collected
## whenever stdlib_cleanup is called.
##
function s_mktempdir() {
	local tmpname=$(mktemp -p "${P_TEMPDIR}" -d)
	local status=$?
	GC_TEMPFILES+=("${tmpname}")
	return ${status}
}


## tempfile_cleanup
##
## Removes temporary files and directories created with s_mktempfile and
## s_mktempdir. Should be called when all temporary files and directories
## are no longer in use.
##
function tempfile_cleanup() {
	for path in "${GC_TEMPFILES[@]}"; do
		if [ -d "${path}" ]; then
			[ "${path}" != "/" ] && rm -rf "${path}"
		else
			rm -f "${path}"
		fi
	done
	return 0
}
